package day05;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Random;

public class NewInstanceTest {

    public static void main(String[] args) throws Exception {
        Class<NewInstanceTest> clazz = NewInstanceTest.class;

        // 新建运行时类的对象
        NewInstanceTest newInstanceTest = clazz.newInstance();
        System.out.println(newInstanceTest);

        // 获取运行时类的控制器并创建对象
        Constructor<NewInstanceTest> constructor = clazz.getConstructor();
        NewInstanceTest newInstanceTest1 = constructor.newInstance();
        System.out.println(newInstanceTest);

        // 获取方法,并执行
        Method instanceTest = clazz.getDeclaredMethod("instanceTest");
        instanceTest.invoke(newInstanceTest1);

        Method[] methods = clazz.getMethods();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m : methods) {

        }

        Class<? super NewInstanceTest> superclass = clazz.getSuperclass();

        Constructor[] constructors = clazz.getConstructors();
        for (Constructor con : constructors) {
            con.getName();
        }

        Class<?>[] interfaces = clazz.getInterfaces();
        Package aPackage = clazz.getPackage();
        Annotation[] annotations = clazz.getAnnotations();

        // 通过反射对象赋值
        Person person = new Person();
        Class<? extends Person> aClass = person.getClass();
        Field field = null;
        try {
            field = aClass.getDeclaredField("name");
            System.out.println(field.getType().getName());
            field.setAccessible(true);
            field.set(person, "xx");
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
        System.out.println(person);
    }

    public void instanceTest() {
        int i = new Random().nextInt(3);
        System.out.println(i);
        String classPath = "";
        switch (i) {
            case 1:
                classPath = "java.lang.String";
                break;
            case 2:
                classPath = "java.util.ArrayList";
                break;
            case 3:
                classPath = "test04.pocker.Person";
                break;
            default:
                classPath = "test04.NewInstanceTest";
                break;
        }
        try {
            Object obj = getInstance(classPath);
            System.out.println(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Object getInstance(String classPath) throws Exception {
        // 通过反射创建运行时类的对象
        Class clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}
